package com.central.apps.handler.timeTask.project;

import com.central.app.common.quartz.QuartzJob;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.apps.service.ProjectCostService;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
//禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
@DisallowConcurrentExecution
public class ProjectUpdateTask extends QuartzJob {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private ProjectCostService projectCostService;

    /**
     * 任务
     *
     * @param context
     * @param jobnum
     * @param jobname
     * @param jobparams
     */
    @SneakyThrows
    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) {
        // 查询项目信息
        List<Map<String, Object>> proList = handlerService.findBySql("select id from gq_proaccount where prostatus = '进行中'");

        if (CollectionUtils.isEmpty(proList)) {
            return;
        }

        for (Map<String, Object> proMap : proList) {
            Integer id = MapUtils.getInteger(proMap, "id");
            Date date = DateUtils.getCurrentDate();
            Map<String, Object> rootTaskMap = handlerService.findOneBySql("select startTime, endTime from gq_scheduleplantask where parentId = 0 and proid = " + id);

            if (rootTaskMap != null && !rootTaskMap.isEmpty()) {
                Date startTime = (Date) MapUtils.getObject(rootTaskMap, "startTime");
                Date endTime = (Date) MapUtils.getObject(rootTaskMap, "endTime");

                long executeDays = DateUtils.daysBetweenExpWeekEnd(startTime, date);
                long unexecuteDays = DateUtils.daysBetweenExpWeekEnd(date, endTime);

                handlerService.updateBySql("update gq_proaccount set executedays = " + executeDays + ", unexecutedays = " + unexecuteDays + " where id = " + id);
            }

            // 更新项目概算成本执行比例
            projectCostService.updProExecuteCost(id);

            // 更新项目预算成本执行比例
            projectCostService.updProPlanExecuteCost(id);
        }
    }
}
